const express = require('express')
const opn = require('opn')
const path = require('path')
const fs = require('fs')
const vueServerRenderer = require('vue-server-renderer')

const app = express()

function start() {
  app.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*')
    res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept,X-Requested-With')
    res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
    res.header('X-Powered-By', ' 3.2.1')
    if (req.method === 'OPTIONS') res.send(200) /* 让options请求快速返回 */
    else next()
  })
  app.get('/', function(req, resp) {
    const filePath = path.join(__dirname, '../dist/bundle.server.js')
    const code = fs.readFileSync(filePath, 'utf8')
    const bundleRenderer = vueServerRenderer.createBundleRenderer(code)
    bundleRenderer.renderToString((err, html) => {
      if (err) {
        console.log(err.message)
        console.log(err.stack)
      }
      console.log(html)
      resp.send(html)
    })
  })
  app.use('/test', (req, resp, next) => {
    resp.send('Test')
  })
  const port = 6622
  app.listen(port, () => {
    console.log(`server started at localhost:${port}`)
    let url = `http://localhost:${port}`
    opn(url)
  })
}

module.exports = start
